package com.ruicar.afs.cloud.channel.witness.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.admin.api.feign.ChannelOnlineSyncService;
import com.ruicar.afs.cloud.channel.common.entity.ApplyMessage;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseApplyService;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.online.service.ChannelOnlineService;
import com.ruicar.afs.cloud.channel.witness.entity.ChannelWitnessInfoTemp;
import com.ruicar.afs.cloud.channel.witness.entity.Message;
import com.ruicar.afs.cloud.channel.witness.service.ChannelWitnessInfoTempService;
import com.ruicar.afs.cloud.channel.witness.utils.WitnessDic;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.job.core.biz.model.ReturnT;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJob;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJobHandler;
import com.ruicar.afs.cloud.common.modules.apply.dto.ChannelCardDTO;
import com.ruicar.afs.cloud.common.modules.apply.enums.CarTypeEnum;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author Ice
 */
@AfsJob
@AllArgsConstructor
@Slf4j
@Component
public class WitnessTask {
    private static final Logger logger = LoggerFactory.getLogger(WitnessTask.class);

    private ChannelWitnessInfoTempService channelWitnessInfoTempService;
    private ChannelConfig channelConfig;
    private ChannelOnlineSyncService channelOnlineSyncService;
    private ChannelUseCaseService channelUseCaseService;
    private final ChannelUseApplyService channelUseApplyService;
    private ChannelOnlineService channelOnlineService;

    @Transactional(rollbackFor = Exception.class)
    @AfsJobHandler(value = "autoWitnessTask")
    public ReturnT<String> satrt(String params) {
        System.out.println("开始============================");
        // 获取今天的毫秒数
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Long dayTime = calendar.getTime().getTime();
        // 给见证人权限
        List<ChannelCardDTO> upIds = new ArrayList<>();
        //同步案件使用
        List<Long> caseList = new ArrayList<>();
        // 声明一个传递过去的数据
        List<Message>  m =new ArrayList<>();
        // 下面的集合用于判断渠道id是否重复
        Set<Long> l =new HashSet<>();

        // 查询所有的通过的见证人信息
        List<ChannelWitnessInfoTemp> list = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getStatus, WitnessDic.STATUS_PASS));
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                // 计算到期时间
                Long endTime = list.get(i).getWitnessValidityAuthorization().getTime();
                if (dayTime > endTime) {
                    list.get(i).setStatus(WitnessDic.STATUS_STOP);
                    list.get(i).setStartStopReason("到期自动停用！");
                    list.get(i).setCeaseTime(new Date(System.currentTimeMillis()));
                    channelWitnessInfoTempService.updateById(list.get(i));


                    // 去停用见证人权限账号  给的数据
                    ChannelCardDTO dto = new ChannelCardDTO();
                    dto.setChannelId(list.get(i).getChannelId());
                    dto.setCard(list.get(i).getWitnessIdCard());
                    if(WitnessDic.BUSINESS_ATTRIBUTES_NEW.equals(list.get(i).getBusinessAttributes())){
                        dto.setBusinessAttributes(CarTypeEnum.newCar);
                    }else {
                        dto.setBusinessAttributes(CarTypeEnum.oldCar);
                    }

                    upIds.add(dto);


                    // 去停用案件信息
                    caseList.add(list.get(i).getId());

                }
                // 获取今天的毫秒数
                long current=System.currentTimeMillis();//当前时间毫秒数
                long zero=current/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
                if((zero+(24*60*60*1000*6))>=endTime&&endTime>=zero){

                    if(l.add(list.get(i).getChannelId())){
                        Message a =new Message();
                        a.setChannelId(list.get(i).getChannelId());
                        a.setCount(1);
                        m.add(a);
                    }else {
                        for (int j=0; j<m.size();j++){
                            if(m.get(j).getChannelId().toString().equals(list.get(i).getChannelId().toString())){
                                m.get(j).setCount(m.get(j).getCount()+1);
                                break;
                            }
                        }
                    }
                }
            }
            // 去停用见证人权限账号
            if(upIds.size()>0){
                Map<String, String> requestHeader = new HashMap<>();
                requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
                requestHeader.put("clientSecret", channelConfig.getApplyAdminClientSecret());
                IResponse result = channelOnlineSyncService.stopWitnessInfo(upIds, requestHeader);
            }
            if(caseList.size()>0){
                // 去停案件
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("clientId", channelConfig.getCaseClientId());
                headers.put("clientSecret", channelConfig.getCaseClientSecret());
                channelUseCaseService.upStatusWitnessByChannelIds(caseList, headers);
            }
            if(m.size()>0){
                List<ApplyMessage> applyMessages =new ArrayList<>();
                Map<String, String> header = new HashMap<>();
                header.put("clientId", channelConfig.getApplyClientId());
                header.put("clientSecret",channelConfig.getApplyClientSecret());

                for (Message e: m) {
                    ChannelBaseInfoTemp a =channelOnlineService.getById(e.getChannelId());
                    ApplyMessage message =new ApplyMessage();
                    message.setChannelId(e.getChannelId());
                    message.setChannelName(a.getChannelFullName());
                    message.setContent("即将有"+e.getCount()+"个见证人在7天内到期！");
                    message.setTitle("见证人到期提醒");
                    message.setSceneType("witness");
                    message.setStatus("0");
                    message.setCreateBy("渠道系统");
                    message.setCreateTime(new Date(System.currentTimeMillis()));
                    applyMessages.add(message);
                }
                channelUseApplyService.saveMessage(applyMessages,header);
            }
        }
        return ReturnT.SUCCESS;
    }
}
